//
//  PersonalInfoController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/4/7.
//  Copyright © 2017年 eaglelive. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class PersonalInfoController:BaseController{
    var personal:PersonalModel!//个人信息
    var personalTable:UITableView!; //数据表格
    var imageView:UIImageView!
    var titleArray:[[String]] = [["头像"],["昵称","手机"],["密码修改", "更换手机号码"]]//行title
    override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        setupNavBar(title: "我的信息", isback: true, appearWay: 2, isright: false)//自定义导航
        //初始化表格
        personalTable=UITableView.init(frame: CGRect(x:0, y:kStatusBarH + kNavigationBarH, width: kScreenW, height: kScreenH), style:UITableViewStyle.grouped)
        personalTable.delegate=self;//实现代理
        personalTable.dataSource=self;//实现数据源
        personalTable.isScrollEnabled = false
        personalTable.showsVerticalScrollIndicator = false
        personalTable.showsHorizontalScrollIndicator = false
        self.view.addSubview(personalTable)
        //初始化退出登陆按钮
        let button:UIButton = UIButton(type:.custom)
        //设置按钮位置和大小
        button.frame = CGRect(x:10, y:370+kNavigationBarH + kStatusBarH, width:kScreenW-20, height:40)
        button.layer.cornerRadius = 10;
        button.backgroundColor = appMainColor
        button.showsTouchWhenHighlighted = true
        button.adjustsImageWhenHighlighted=false
        //设置按钮文字
        button.setTitle("退出登录", for:.normal)
        button.addTarget(self, action: #selector(logoutBtnClick(sender:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(button)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        personal = PersonalModel.loadPersonalFromDB(id: userID as! String)//查询用户信息
        personalTable.reloadData()
    }
}
extension PersonalInfoController{
    //退出登陆方法 跳转去登陆页
    func logoutBtnClick(sender: UIButton){
        print("我退出登录啦")
        if(PersonalModel.deletePersonal(userID: personal.userID)){
            let userDefault = UserDefaults.standard
            userDefault.removeObject(forKey: "userID")
            userDefault.removeObject(forKey: "tokenID")
            userDefault.removeObject(forKey: "isEmployee")
            let mainVC = UINavigationController(rootViewController: LoginController())
            app.window?.rootViewController = mainVC
        }
    }
    //弹出选择相机还是相册
    func choicePicture(){
        let alert = UIAlertController()
        let cleanAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler:nil)
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        let photoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            if UIImagePickerController.isSourceTypeAvailable(.camera){
                //指定图片控制器类型
                picker.sourceType = UIImagePickerControllerSourceType.camera
                //弹出控制器，显示界面
                self.present(picker, animated: true, completion: nil)
            }else{
                print("相机调用失败")
            }
        }
        let choseAction = UIAlertAction(title: "从手机相册选择", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                //指定图片控制器类型
                picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
                //弹出控制器，显示界面
                self.present(picker, animated: true, completion: nil)
            }else{
                print("读取相册失败")
            }
        }
        alert.addAction(cleanAction)
        alert.addAction(photoAction)
        alert.addAction(choseAction)
        self.present(alert, animated: true, completion: nil)
    }
}
extension PersonalInfoController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //选择图片成功后代理
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [String : Any]) {
        if reachability.isReachable {
            //显示的图片
            let image:UIImage =  info[UIImagePickerControllerOriginalImage] as! UIImage
            
            uploadImage(img: image)//上传图片到服务器
            picker.dismiss(animated: true, completion: nil)//图片控制器退出
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //上传图片
    func uploadImage(img:UIImage){
        let toUrl = "\(projectUrl)/user/updateUserIcon/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
        let imageData = UIImageJPEGRepresentation(img, 1.0)!
        //使用Alamofire上传
        Alamofire.upload(multipartFormData: { (mult) in
            mult.append(imageData, withName: "file", fileName: "pickedimage.jpg", mimeType: "image/jpeg")
        }, to: toUrl, encodingCompletion: { (result) in
            self.imageView.image = img
            switch result {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    let jsonString = response.result.value!
                    let jsonDate = JSON(jsonString)
                    if jsonDate["success"] == true {
                        let photoID = jsonDate["rdata"].rawValue as! String
                        if(PersonalModel.changeIcon(newIcon: photoID, userID: userID as! String)){
                            print("图片上传成功!")
                        }
                    }else{
                        self.failOperNoticeFun(code: jsonDate["rcode"].rawString()!, message: jsonDate["rdata"].rawString()!)
                    }
                }
            case .failure(let encodingError):
                print("ERROR RESPONSE: \(encodingError)")
            }
            print("result:\(result)")
        })
    }
}
//UITableView 代理 & 数据源
extension PersonalInfoController:UITableViewDataSource, UITableViewDelegate{
    //表头部高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    //底部高度
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        return 0.1
    }
    //段数
    func numberOfSections(in tableView: UITableView) -> Int {
        return titleArray.count
    }
    //行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let subTitleArr = titleArray[section]
        return subTitleArr.count
    }
    //行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if indexPath.section == 0 {
            return 80
        }
        return 44
    }
    //cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellId="cellId";
        var cell=tableView.dequeueReusableCell(withIdentifier: cellId)
        if(cell == nil){
            cell=UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: cellId);
        }
        let subTextArr = titleArray[indexPath.section]
        if(indexPath.section == 0){//设置图像
            imageView = UIImageView()
            let url = "\(projectUrl)/file/download/\(personal.icon)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            imageView.sd_setImage(with: URL.init(string: url), placeholderImage: UIImage.init(named: "personal_default"))
            imageView.layer.cornerRadius = 35.0
            imageView.layer.masksToBounds = true
            imageView.layer.borderColor = UIColor.white.cgColor
            imageView.layer.borderWidth = 2.0
            imageView.layer.rasterizationScale = UIScreen.main.scale
            imageView.layer.shouldRasterize = true
            imageView.frame = CGRect(x:kScreenW - 100, y: kNavigationBarH + kStatusBarH + 15, width: 70, height: 70)
            self.view.addSubview(imageView)
            
        }
        if(indexPath.section == 1 && indexPath.row == 0){//昵称
            cell?.detailTextLabel?.text = personal.nickName
        }
        if(indexPath.section == 1 && indexPath.row == 1){//手机
            cell?.detailTextLabel?.text = personal.phoneNum
        }
        //去掉手机后面的有转向箭头
        if(indexPath.section == 1 && indexPath.row == 1){
            cell?.accessoryType = UITableViewCellAccessoryType.none
        }else{
            cell?.accessoryType=UITableViewCellAccessoryType.disclosureIndicator
        }
        cell?.textLabel?.text = subTextArr[indexPath.row];
        cell?.textLabel?.font = UIFont .systemFont(ofSize: CGFloat(15))
        cell?.detailTextLabel?.font = UIFont .systemFont(ofSize: CGFloat(13))
        return cell!
    }
    //选中cell时触发这个代理
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: false)//点击完成，取消高亮
        if(indexPath.section == 0 && indexPath.row == 0){//修改图像
            choicePicture()
        }
        if(indexPath.section == 1 || indexPath.section == 2){
            if(indexPath.section == 1 && indexPath.row == 0){//修改昵称
                let vc = UpdateNickName()
                vc.personal = personal
                self.navigationController?.present(vc, animated: true, completion: nil)
            }
            if(indexPath.section == 2 && indexPath.row == 0){//修改密码
                let vc = UpdatePwdController()
                vc.personal = personal
                self.navigationController?.present(vc, animated: true, completion: nil)
            }
            if(indexPath.section == 2 && indexPath.row == 1){//修改手机号码
                let vc = UpdatePhoneController()
                vc.personal = personal
                self.navigationController?.present(vc, animated: true, completion: nil)
            }
        }
    }
}
